package com.czmh.etc.onlinepubsys.wx.services.impl;


import com.alibaba.fastjson.JSON;
import com.czmh.etc.onlinepubsys.wx.services.IWeixinOAuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.weixin4j.Weixin;
import org.weixin4j.WeixinBuilder;
import org.weixin4j.WeixinException;
import org.weixin4j.component.SnsComponent;
import org.weixin4j.model.base.Token;
import org.weixin4j.model.js.Ticket;
import org.weixin4j.model.sns.SnsAccessToken;

import java.io.UnsupportedEncodingException;

/**
 * @ClassName
 * @Description TODO
 * @Author Eric
 * @Date 2019-06-08 01:16
 * @Version 1.0v
 */
@Service
public class WeixinOAuthServiceImpl implements IWeixinOAuthService {

    private Logger logger = LoggerFactory.getLogger(WeixinOAuthServiceImpl.class);


    /**
     * 用户同意授权，获取code
     *
     * @param appid       公众号的唯一标识
     * @param redirectUri 授权后重定向的回调链接地址， 请使用 urlEncode 对链接进行处理
     *                    scope为snsapi_base
     * @return
     */
    @Override
    public String getOAuth2CodeBySnsapiBase(String appid, String redirectUri) throws UnsupportedEncodingException {
        logger.info("页面授权SnsapiBase:code:{} redirectUri:{}", appid, redirectUri);
        WeixinBuilder b = WeixinBuilder.newInstance();
        Weixin weixin = b.build();
        SnsComponent snsComponent = weixin.sns();
        return snsComponent.getOAuth2CodeBaseUrl(redirectUri);

    }

    /**
     * 用户同意授权，获取code
     *
     * @param appid       公众号的唯一标识
     * @param redirectUri 授权后重定向的回调链接地址， 请使用 urlEncode 对链接进行处理
     *                    scope为snsapi_userinfo
     * @return
     */
    @Override
    public String getOAuth2CodeBySnsapiserinfo(String appid, String redirectUri) throws UnsupportedEncodingException {
        logger.info("页面授权Snsapiserinfo:code:{} redirectUri:{}", appid, redirectUri);
        WeixinBuilder b = WeixinBuilder.newInstance();
        Weixin weixin = b.build();
        SnsComponent snsComponent = weixin.sns();
        return snsComponent.getOAuth2CodeUserInfoUrl(redirectUri);

    }

    /**
     * 通过code换取网页授权access_token
     *
     * @param appid  微信appid
     * @param secret 微信secret
     * @param code   填写第一步获取的code参数
     * @return OAuth2Token
     */
    @Override
    public SnsAccessToken getOauthToken(String appid, String secret, String code) throws WeixinException {
        logger.info("通过code换取网页授权access_token:appid:{}   secret:{}    code:{}", appid, secret, code);
        WeixinBuilder b = WeixinBuilder.newInstance();
        Weixin weixin = b.build();
        SnsComponent snsComponent = weixin.sns();
        SnsAccessToken snsAccessToken = snsComponent.getSnsOAuth2AccessToken(code);
        logger.info("获取token返回来数据：json:{}", snsAccessToken);
        return snsAccessToken;
    }

    /**
     * 刷新token
     *
     * @param appid    appid
     * @param oldToken 旧token值
     * @return
     */
    @Override
    public SnsAccessToken refreshToken(String appid, String oldToken) {
        logger.info("刷新token:appid:{}  dToken:{}", appid, oldToken);
        WeixinBuilder b = WeixinBuilder.newInstance();
        Weixin weixin = b.build();
        SnsComponent snsComponent = weixin.sns();
        SnsAccessToken snsAccessToken = null;
        try {
            snsAccessToken = snsComponent.refreshToken(oldToken);
        } catch (WeixinException e) {
            e.printStackTrace();
            logger.info("刷新token异常数据返回来数据：json:{}", e.getMessage());
        }
        logger.info("刷新token得到数据返回来数据：json:{}", snsAccessToken != null ? JSON.toJSONString(snsAccessToken) : null);
        return snsAccessToken;
    }


    /**
     * 检验授权凭证（access_token）是否有效
     *
     * @param accessToken accessToken
     * @param openId      openId
     * @return
     */
    @Override
    public boolean isAuth(String accessToken, String openId) {
        logger.info("获取用户信息:openId:{}  accessToken:{}", openId, accessToken);
        WeixinBuilder b = WeixinBuilder.newInstance();
        Weixin weixin = b.build();
        SnsComponent snsComponent = weixin.sns();
        boolean r = false;
        try {
            r = snsComponent.validateAccessToken(accessToken, openId);
        } catch (WeixinException e) {
            e.printStackTrace();
            logger.info("获取用户信息异常:openId:{}  accessToken:{}", e.getMessage());
            r = false;
        }
        return r;
    }

    /**
     * 获取微信token
     *
     * @return
     */
    @Override
    public Token getToken() {
        logger.info("获取微信token");
        WeixinBuilder b = WeixinBuilder.newInstance();
        Weixin weixin = b.build();
        try {
            return weixin.getToken();
        } catch (WeixinException e) {
            e.printStackTrace();
            logger.info("获取微信token异常:", e.getMessage());
            return null;
        }
    }

    /**
     * 根据token 获取getTicket
     *
     * @return
     */
    @Override
    public Ticket getTicket() {
        logger.info("获取微信Ticket");
        WeixinBuilder b = WeixinBuilder.newInstance();
        Weixin weixin = b.build();
        Ticket ticket = null;
        try {
            ticket = weixin.getJsApiTicket();
        } catch (WeixinException e) {
            e.printStackTrace();
            logger.info("获取微信Ticket异常:", e.getMessage());
        }
        logger.info("获取微信Ticket返回来数据：json:{}", ticket != null ? JSON.toJSONString(ticket) : null);
        return ticket;
    }
}
